package com.sunny.ynhz.utils;

import android.content.Context;
import android.graphics.Color;
import android.util.Log;

import com.github.mikephil.charting.charts.HorizontalBarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.MarkerView;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.sunny.ynhz.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by huhuan123 on 2018/8/8.
 *
 * @describe TODO
 */

public class ChartUtils {

    /**
     * 初始化图表
     */
    public static void initPieView(String[] Stars, int[] number, PieChart mPiechart) {
        setData(Stars, number, mPiechart);
        //设置X轴的动画
        mPiechart.animateX(1400);
        //使用百分比
        mPiechart.setUsePercentValues(true);
        //设置图列可见
        mPiechart.getLegend().setEnabled(true);

        //设置图列标识的大小
        mPiechart.getLegend().setFormSize(10);
        //设置图列标识文字的大小
        mPiechart.getLegend().setTextSize(10);
        mPiechart.setDrawSliceText(false);
        //设置图列的位置
        Legend mLegend = mPiechart.getLegend();  //设置比例图
        mLegend.setPosition(Legend.LegendPosition.RIGHT_OF_CHART);  //最右边显示
//          mLegend.setForm(Legend.LegendForm.LINE);  //设置比例图的形状，默认是方形
        mLegend.setXEntrySpace(7f);
        mLegend.setYEntrySpace(5f);
        //设置图列标识的形状
        mPiechart.getLegend().setForm(Legend.LegendForm.SQUARE);
        //设置图表描述
        mPiechart.getDescription().setText("");
        mPiechart.setRotationEnabled(true);
    }

    /**
     * 图表设置数据
     */
    public static void setData(String[] Stars, int[] number, PieChart mPiechart) {
        //设置标题
        ArrayList<String> titles = new ArrayList<>();
        for (int i = 0; i < Stars.length; i++) {
            titles.add(Stars[i]);
        }
        ArrayList<PieEntry> entrys = new ArrayList<>();
        for (int i = 0; i < number.length; i++) {
            entrys.add(new PieEntry(number[i], Stars[i], i));
        }
        //饼图数据集
        PieDataSet dataset = new PieDataSet(entrys, "");
        //设置饼状图Item之间的间隙
        dataset.setSliceSpace(3);
        //饼图Item被选中时变化的距离
        dataset.setSelectionShift(10f);

        //颜色填充
        dataset.setColors(new int[]{Color.parseColor("#82E2E6"), Color.parseColor("#FB8DA8"), Color.parseColor("#FFB198"), Color.parseColor("#58D0ED"), Color.parseColor("#AA66CC")});

        //数据填充
        PieData piedata = new PieData(dataset);
        //设置饼图上显示数据的字体大小
        piedata.setValueTextSize(10);
        mPiechart.setData(piedata);


    }

    public static void initHorBar(HorizontalBarChart mChart, ArrayList<Float> mList, ArrayList<String> mCityName) {
//        mChart.setOnChartValueSelectedListener(this);
        // mChart.setHighlightEnabled(false);

        mChart.setDrawBarShadow(false);

        mChart.setDrawValueAboveBar(true);

        mChart.getDescription().setEnabled(false);

        // if more than 60 entries are displayed in the chart, no values will be
        // drawn
        mChart.setMaxVisibleValueCount(60);


        // scaling can now only be done on x- and y-axis separately
        mChart.setPinchZoom(false);
//        mChart.setBackgroundColor(Color.WHITE);
//        mChart.setDrawBorders(false);

        // draw shadows for each bar that show the maximum value
        // mChart.setDrawBarShadow(true);


        mChart.setDrawGridBackground(false);
        mChart.setScaleEnabled(false);
        XAxis xl = mChart.getXAxis();
        xl.setPosition(XAxis.XAxisPosition.BOTTOM);
//        xl.setTypeface(mTfLight);
        xl.setDrawAxisLine(false);
        xl.setDrawGridLines(false);
        xl.setCenterAxisLabels(false);
        xl.setGranularity(1f);
        xl.setEnabled(true);
        xl.setLabelCount(mList.size());
        xl.setTextColor(Color.parseColor("#666666"));
        xl.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                if (((int) value >= 0 && (int) value < mCityName.size()))
                    return mCityName.get((int) value);
                else
                    return "";
            }
        });


        YAxis yl = mChart.getAxisLeft();
        yl.setDrawAxisLine(false);
        yl.setDrawGridLines(false);
        yl.setDrawLabels(false);

        yl.setAxisMinimum(0f); // this replaces setStartAtZero(true)


        YAxis yr = mChart.getAxisRight();
        yr.setDrawAxisLine(false);
        yr.setDrawGridLines(false);
        yr.setAxisMinimum(0f);
        yr.setTextColor(Color.parseColor("#666666"));
        setData(mChart, mList);
        mChart.setFitBars(true);
        mChart.animateY(2500);

        Legend l = mChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
        l.setFormSize(8f);
        l.setXEntrySpace(4f);
        l.setEnabled(false);
    }

    private static void setData(HorizontalBarChart mChart, ArrayList<Float> mList) {

        float barWidth = 0.8f;
        if (mList.size() == 1||mList.size()==2||mList.size()==3) {
            barWidth = 0.1f;
        }

        float spaceForBar = 1f;
        ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();

        for (int i = 0; i < mList.size(); i++) {
            yVals1.add(new BarEntry(i * spaceForBar, mList.get(i), null));
        }
        BarDataSet set1;
        if (mChart.getData() != null &&
                mChart.getData().getDataSetCount() > 0) {
            set1 = (BarDataSet) mChart.getData().getDataSetByIndex(0);
            set1.setValues(yVals1);
            set1.setColor(Color.parseColor("#5BA1FA"));
            set1.setBarBorderColor(Color.WHITE);
            set1.setBarShadowColor(Color.WHITE);
            set1.setHighlightEnabled(false);
            mChart.getData().notifyDataChanged();
            mChart.notifyDataSetChanged();
        } else {
            set1 = new BarDataSet(yVals1, "");
            set1.setDrawIcons(false);
            set1.setColor(Color.parseColor("#5BA1FA"));
            set1.setBarBorderColor(Color.WHITE);
            set1.setBarShadowColor(Color.WHITE);
            set1.setHighlightEnabled(false);
            ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
            dataSets.add(set1);
            BarData data = new BarData(dataSets);
            data.setValueTextSize(10f);
//            data.setValueTypeface(mTfLight);
            data.setBarWidth(barWidth);
            mChart.setData(data);
        }
    }

    /**
     * 初始化图表
     */
    public static void initChart(LineChart lineChart, Context context) {
        /***图表设置***/
        //是否展示网格线
        lineChart.setDrawGridBackground(false);
        //是否显示边界
        lineChart.setDrawBorders(true);
        //是否可以拖动
        lineChart.setDragEnabled(false);
        //是否有触摸事件
        lineChart.setTouchEnabled(true);
        //设置XY轴动画效果
        lineChart.animateY(2500);
        lineChart.animateX(1500);


        /***XY轴的设置***/
        XAxis xAxis = lineChart.getXAxis();
        YAxis leftYAxis = lineChart.getAxisLeft();
        YAxis rightYaxis = lineChart.getAxisRight();
        //X轴设置显示位置在底部
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisMinimum(0f);
        xAxis.setGranularity(1f);
        //保证Y轴从0开始，不然会上移一点
        leftYAxis.setAxisMinimum(0f);
        rightYaxis.setAxisMinimum(0f);


        /***折线图例 标签 设置***/
        Legend legend = lineChart.getLegend();
        //设置显示类型，LINE CIRCLE SQUARE EMPTY 等等 多种方式，查看LegendForm 即可
        legend.setForm(Legend.LegendForm.LINE);
        legend.setTextSize(12f);
        //显示位置 左下方
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        //是否绘制在图表里面
        legend.setDrawInside(false);

        lineChart.setBackgroundColor(Color.WHITE);
        lineChart.setDrawBorders(false);
        lineChart.setDrawGridBackground(false);
        xAxis.setDrawGridLines(false);
        xAxis.setLabelCount(12);
        rightYaxis.setDrawGridLines(false);
        leftYAxis.setDrawGridLines(true);
        rightYaxis.setDrawLabels(false);
        rightYaxis.setDrawGridLines(false);
        rightYaxis.setEnabled(false);
        leftYAxis.setTextColor(Color.parseColor("#A5A5A5"));
    }

    /**
     * 曲线初始化设置 一个LineDataSet 代表一条曲线
     *
     * @param lineDataSet 线条
     * @param color       线条颜色
     * @param mode
     */
    public static void initLineDataSet(LineDataSet lineDataSet, int color, LineDataSet.Mode mode) {
        lineDataSet.setColor(color);
        lineDataSet.setCircleColor(color);
        lineDataSet.setLineWidth(0.5f);
        lineDataSet.setCircleRadius(2f);
        //设置曲线值的圆点是实心还是空心
        lineDataSet.setDrawCircleHole(false);
        lineDataSet.setValueTextSize(10f);
        //设置折线图填充
        lineDataSet.setDrawFilled(true);


        lineDataSet.setFormLineWidth(1f);
        lineDataSet.setFormSize(15.f);
        if (mode == null) {
            //设置曲线展示为圆滑曲线（如果不设置则默认折线）
            lineDataSet.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        } else {
            lineDataSet.setMode(mode);
        }

    }

    /**
     * 添加曲线
     */
    public static void addLine(List<Float> dataList, String name, int color, LineChart lineChart) {
        List<Entry> entries = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {
            Entry entry = new Entry(i, dataList.get(i));
            entries.add(entry);
        }
        // 每一个LineDataSet代表一条线
        LineDataSet lineDataSet = new LineDataSet(entries, name);

        initLineDataSet(lineDataSet, color, LineDataSet.Mode.LINEAR);
        lineChart.getLineData().addDataSet(lineDataSet);
        lineDataSet.setDrawValues(false);
        lineDataSet.notifyDataSetChanged();
        lineChart.notifyDataSetChanged();
        lineChart.invalidate();
    }

    /**
     * 展示曲线
     *
     * @param dataList 数据集合
     * @param name     曲线名称
     * @param color    曲线颜色
     */
    public static void showLineChart(List<Integer> dataList, String name, int color, LineChart lineChart, String title[]) {

        List<Entry> entries = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {

            /**
             * 在此可查看 Entry构造方法，可发现 可传入数值 Entry(float x, float y)
             * 也可传入Drawable， Entry(float x, float y, Drawable icon) 可在XY轴交点 设置Drawable图像展示
             */
            Entry entry = new Entry(i, dataList.get(i));
            entries.add(entry);
        }
        XAxis xAxis = lineChart.getXAxis();
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return (title[(int) value]) + "月";
            }
        });
        xAxis.setTextColor(Color.parseColor("#A5A5A5"));
        xAxis.setTextSize(8f);
        // 每一个LineDataSet代表一条线
        LineDataSet lineDataSet = new LineDataSet(entries, name);
        initLineDataSet(lineDataSet, color, LineDataSet.Mode.LINEAR);
        LineData lineData = new LineData(lineDataSet);
        lineData.setDrawValues(false);
        lineChart.setData(lineData);
        lineChart.getDescription().setText("");
        lineChart.invalidate();
    }


}
